<template>
  <div class="bar-chart-container" v-loading="loading">
    <!-- 暂无数据 -->
    <noData
      v-show="isNoData"
      :title="title"
      :sub-title="params.organizationName.value"
      :year="params.queryParams.inventoryYear"
    />
    <div v-show="!isNoData" class="chart-box">
      <div class="chart-title">
        <p class="title">{{ title }}(单位: t CO₂e)</p>
        <p class="sub-title"
          ><span>{{ params.organizationName.value }}</span>
          <el-divider v-if="params.queryParams.inventoryYear" direction="vertical" />
          <span v-if="params.queryParams.inventoryYear"
            >{{ params.queryParams.inventoryYear }}年</span
          >
        </p>
      </div>
      <GroupBarChart
        :barData="barData"
        v-if="orgType === 'GROUP' && barData.orgGhgSourceStaticList?.length"
      />
      <FactoryBarChart
        :factoryBarData="factoryBarData"
        v-if="orgType === 'FACTORY' && factoryBarData?.length"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, watch, inject, computed, ComputedRef, onMounted, Ref } from 'vue';
import { queryOrgByGhgSourceAnalysis } from '@/apis/eci/visualAnalysis';
import noData from '../../../noData/index.vue';
import {
  queryAnalysisParams,
  OrgGhgSourceStaticListItem
} from '@/apis/eci/visualAnalysis/model/visualAnalysisModel';
import { kgToT } from '@/utils';
import FactoryBarChart from './components/FactoryBarChart/index.vue';
import GroupBarChart from './components/GroupBarChart/index.vue';
import type { BarDataType } from './components/GroupBarChart/types';

interface injectParams {
  queryParams: queryAnalysisParams;
  organizationName: ComputedRef;
  orgType: Ref<'GROUP' | 'FACTORY'>;
}
const props = defineProps(['month']);
const loading = ref(false);
const barData = ref<BarDataType>({
  organizationName: [],
  orgGhgSourceStaticList: [
    {
      name: '',
      data: [] as any[]
    }
  ]
});
const factoryBarData = ref<{ name: string; value: number }[]>([]);
const params = inject('params') as injectParams;
/**
 * 组织类型 集团|工厂
 */
const orgType = computed(() => {
  return params.orgType.value || 'GROUP';
});

const title = computed(() => {
  return orgType.value === 'FACTORY' ? '工厂能源排放分布分析' : '碳排放量按排放源分布分析';
});
// 监听月份\顶部参数是否发生改变，改变重置 Echart
//
watch([() => props.month, params.queryParams], () => {
  loadBarData();
});
const loadBarData = async () => {
  try {
    if (params.queryParams.inventoryYear) {
      loading.value = true;
      const res = await queryOrgByGhgSourceAnalysis({
        ...params.queryParams,
        dataPeriod: props.month
      });
      // 工厂视角
      if (orgType.value === 'FACTORY') {
        factoryBarData.value = (res.orgGhgSourceStaticList as OrgGhgSourceStaticListItem[])
          .map(item => {
            return {
              name: item.name,
              value: kgToT(Number(item.itemList[0].totalEmission))
            };
          })
          .sort((a, b) => {
            return b.value - a.value;
          });

        barData.value = {
          organizationName: [],
          orgGhgSourceStaticList: []
        };
        return;
      } else {
        factoryBarData.value = [];
      }

      barData.value = {
        organizationName: res.organizationName, // 工厂名数组（x轴）
        orgGhgSourceStaticList:
          (res.orgGhgSourceStaticList as OrgGhgSourceStaticListItem[])
            .map(item => {
              return {
                name: item.name,
                data: item.itemList.map((i, index) => {
                  return {
                    organizationName: i.organizationName,
                    totalEmission: kgToT(Number(i.totalEmission)),
                    totalEmissionRate: i.totalEmissionRate,
                    value: item.data[index]
                  };
                })
              };
            })
            .sort((a, b) => {
              if (b.data?.length && a.data?.length) {
                return b.data[0].totalEmission - a.data[0].totalEmission;
              } else {
                return -1;
              }
            }) || []
      };
    }
  } catch (error) {
    console.log('error', error);
    factoryBarData.value = [];
    barData.value = {
      organizationName: [],
      orgGhgSourceStaticList: []
    };
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadBarData();
});

const isNoData = computed(() => {
  if (orgType.value === 'FACTORY') {
    return !factoryBarData.value?.length;
  }
  if (barData.value) {
    return barData.value.organizationName.length === 0;
  } else {
    return true;
  }
});
</script>

<style lang="scss" scoped>
.echarts-tooltip {
  max-height: 50px;
}
.bar-chart-container {
  // flex: 1;
  width: 100%;
  height: 100%;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(67, 89, 112, 0.08);
  border-radius: 6px;

  .chart-box {
    height: 100%;
    .chart-title {
      height: 70px;
      padding: 13px 20px;
      border-bottom: 1px solid #ebeff2;
      .title {
        font-size: 14px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 700;
        color: #0a1f33;
        line-height: 22px;
      }
      .sub-title {
        font-size: 12px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #7a8a99;
        line-height: 20px;
      }
    }
  }
}
</style>
